package com.tang.net;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.tang.base.BaseResponse;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * CreateTime: 2016-04-03下午9:18
 * Author: wjkjinke00@126.com
 * Description:
 */
final class MyGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private final Gson gson;
    private final Type type;

    MyGsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }


    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        boolean code = response.contains("code");
        try {
            String decode = "";
            if (!code) {
                decode = "{\"code\":200,\"message\":\"获取成功\",\"data\":null}";
                JSONObject jo = new JSONObject(decode);
                jo.put("data", response);
                decode = jo.toString();
            } else {
                decode = ResponseDecoder.decode(response);
            }
            Log.e("ResponseBody", decode);
            return gson.fromJson(decode, type);
        } catch (JSONException e) {
            e.printStackTrace();
//            String decode = "{\"code\":-1,\"message\":\"服务器开小差了!\",\"data\":null}";
            return gson.fromJson(response, type);
        } finally {
            value.close();
        }
    }

}
